import pandas as pd
from keras import models
from keras import layers
from keras.layers import Dropout
from keras.layers import regularizers
from matplotlib import pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
# 导入 数据库的工具
from conDatabase import dataUtils
datautils = dataUtils()

class getPre:
    def __init__(self):
        print("initial code")

    def getAns(self,var):
        print("begin loading date")

        data = datautils.selectDayrecordsAndTime(var)
        # 转化为 Array
        y = np.array(data[:, 0])
        x = np.array(data[:, 1:5])

        # 转化为 Array
        x = np.array(x)
        y = np.array(y)

        # 打印出数据信息
        print("x size is ", x.shape)
        # (380, 4)
        print("y size is ", y.shape)
        # (380, 1)

        # 划分训练集， 测试集
        x_train, x_test,y_train,y_test = train_test_split(x, y,test_size=0.2,shuffle=True)

        print("x_train size is ", x_train.shape)
        # (304, 4)

        print("x_test size is ", x_test.shape)
        # (76, 4)
        print("y_train size is  ", y_train.shape)
        # (304,)
        print("y_test size is ", y_test.shape)
        # (76,)


        # 数据规格化
        # mean = x_train.mean(axis = 0)
        # print("mean:", mean)
        # x_train -= mean
        # std = x_train.std(axis = 0)
        # print("std:", std)
        # x_train /= std
        # x_test -= mean
        # x_test /= std
        # 搭建全连接神经网络

        print(x_train)

        model = models.Sequential()
        model.add(layers.Dense(64, activation='relu', input_shape=(x_train.shape[1], )))
        model.add(Dropout(0.2))
        model.add(layers.Dense(64, activation='relu',
                                kernel_regularizer=regularizers.l2(0.01),
                               activity_regularizer=regularizers.l1_l2(0.01)
                               )
                  )
        model.add(layers.Dense(1))
        # 打印网络层次结构
        print(model.summary())
        model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
        history = model.fit(x_train, y_train, epochs=1000, batch_size=200, verbose=2, validation_data=(x_test, y_test))

        pre = model.predict(x_train)

        print(pre)

        print(y_train)


        print("ans:", pre[-1])

        model.save('PrePeople'+var+'.h5')

        return  pre[-1]
        # 标题显示中文
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        plt.plot(np.arange(304), pre, "r^")
        plt.plot(np.arange(304), y_train, "bs")
        plt.title("蓝色为真实数据, 红色为预测数据")
        plt.show()


